//
//  HomeTableViewCell.swift
//  WBDemo
//
//  Created by Jin on 08/05/2018.
//  Copyright © 2018 com.baidu.123. All rights reserved.
//

import UIKit
import SDWebImage

class HomeTableViewCell: UITableViewCell {

    private let edgeMargin : CGFloat = 15
    private let itemMargin : CGFloat = 10
    //微博正文宽度约束
    @IBOutlet weak var contentLabelWcons:NSLayoutConstraint!
    @IBOutlet weak var picUrlViewWcons:NSLayoutConstraint!
    @IBOutlet weak var picUrlViewHcons:NSLayoutConstraint!
    @IBOutlet weak var picUrlViewBottomCons:NSLayoutConstraint!
    @IBOutlet weak var retweetedLabelTopCons:NSLayoutConstraint!
    
    @IBOutlet weak var iconView:UIImageView!
    @IBOutlet weak var verifiedView:UIImageView!
    @IBOutlet weak var vipView:UIImageView!
    @IBOutlet weak var timeLabel:UILabel!
    @IBOutlet weak var sourceLabel:UILabel!
    @IBOutlet weak var contentLabel:UILabel!
    @IBOutlet weak var screenNameLabel:UILabel!
    @IBOutlet weak var retweetedLabel:UILabel!//转发微博正文
    @IBOutlet weak var retweetedBgView:UIView!//转发微博背景
    @IBOutlet weak var picUrlView:PicUrlsCollectionView!
    
    var picUrls:[URL] = [URL]() //配图数组
    
    //自定义属性
    var status : HomeViewModel? {
        didSet{
            //0.nil值校验
            guard let status = status else {
                return
            }
            
            //1.处理微博来源字符串
            var sourceText:String?
            if let source = status.source, source != "" {
                let startIndex = (status.source! as NSString).range(of: ">").location + 1
                let length = (status.source! as NSString).range(of: "</").location - startIndex
                sourceText = (status.source! as NSString).substring(with: NSRange(location: startIndex, length: length))
            }
            //2.处理微博发布日期
            timeLabel.text = Date().createDateString(createAt: status.created_at)
            
            //3.处理用户验证等级
            switch status.verified_type {
            case 0:     //个人认证
                verifiedView.image = UIImage(named: "avatar_vip")
                break
            case 2,3,5: //企业认证
                verifiedView.image = UIImage(named: "avatar_enterprise_vip")
                break
            case 220:   //微博达人
                verifiedView.image = UIImage(named: "avatar_grassroot")
                break
            default:
                break
            }
            //4.处理用户会员等级
            vipView.image = UIImage(named: "common_icon_membership_level\(status.mbrank)")
            //5.微博正文
            contentLabel.text = status.text
            //6.微博来源
            sourceLabel.text = sourceText
            //7.微博头像
            iconView.sd_setImage(with: URL(string: status.profile_image_url!), placeholderImage: UIImage(named:"avatar_default_small"), options: [], completed: nil)
            //8.用户昵称
            screenNameLabel.text = status.screen_name
            screenNameLabel.textColor = status.mbrank > 6 ? UIColor.black : UIColor.orange
            //9.处理配图数据
            let picURLDicts = status.pic_urls?.count != 0 ? status.pic_urls : status.retweeted_status?.pic_urls
            
            if let picURLDicts = picURLDicts {
                for dict in picURLDicts {
                    let url = URL(string:dict["thumbnail_pic"]!)
                    picUrls.append(url!)
                }
                
                let picViewSize = calculatePicUrlViewSize(count: picUrls.count)
                picUrlViewHcons.constant = picViewSize.height
                picUrlViewWcons.constant = picViewSize.width
                //9.1将配图URL数组传递到CollectionView进行处理
                picUrlView.picUrls = picUrls
                //9.2清空配图数组
                picUrls = []
            }
            //10.处理转发微博
            if status.retweeted_status != nil {
                retweetedLabel.text = "@" + (status.retweeted_status?.screen_name)! + ": " + (status.retweeted_status?.text)!
                retweetedBgView.isHidden = false
                retweetedLabelTopCons.constant = 10
            }else {
                retweetedLabel.text = nil
                retweetedBgView.isHidden = true
                retweetedLabelTopCons.constant = 0
            }
           
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
       
        //设置微博正文宽度约束
        contentLabelWcons.constant = UIScreen.main.bounds.width - 2 * edgeMargin

    }
}

extension HomeTableViewCell {
    private func calculatePicUrlViewSize(count:Int) -> CGSize {
        //0.没有配图
        if count == 0 {
            //collectionView底部约束设置为0
            picUrlViewBottomCons.constant = 0
            return CGSize.zero
        }
        
        //collectionView底部约束设置为10
        picUrlViewBottomCons.constant = 10
        
        //1.取出picView布局
        let layout = picUrlView.collectionViewLayout as! UICollectionViewFlowLayout
        
        //2.处理单张配图 http://wx3.sinaimg.cn/thumbnail/4dccf617gy1fr46h7a5zkj20lw6e21kx.jpg
        if count == 1 {
            guard let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey:self.picUrls.last?.absoluteString) else {
                return CGSize.zero
            }
            layout.itemSize = CGSize(width: image.size.width * 2, height: image.size.height * 2)
            return CGSize(width: image.size.width * 2, height: image.size.height * 2)
        }
        //3.处理多张配图itemSize
        let imageViewWH = (UIScreen.main.bounds.width - 2 * edgeMargin - 2 * itemMargin) / 3
        layout.itemSize = CGSize(width: imageViewWH, height: imageViewWH)
        
        //4.四张配图,田字型
        if count == 4 {
            let picViewWH = imageViewWH * 2 + itemMargin * 1.01
            return CGSize(width: picViewWH, height: picViewWH)
        }
        //5.其他张配图
        let rows = CGFloat((count - 1) / 3 + 1)
        let picViewH = rows * imageViewWH + (rows - 1) * itemMargin
        let picViewW = UIScreen.main.bounds.width - 2 * edgeMargin
        return CGSize(width: picViewW, height: picViewH)
    }
}
